<?php


namespace app\model;

use think\facade\Db;
use think\Model;
use app\model\Attachment as AttachmentModel;
use app\common\library\Translation;

use app\model\RemarkModel;
use app\model\CarModel;
use app\model\DriverModel;
class ClearanceModel extends Model
{
    protected $table = "store_clearance";

    /**
     * @param $param
     * @return ClearanceModel|array|int|mixed|Model|null
     * @notes 请求通关服务
     * @author: dongdong
     * @date: 2025/2/19 11:35
     */
    public function request_clearance($param){
        Db::startTrans();
        $Translation = new Translation();
        $AttachmentModel = new AttachmentModel();

        try {
            $d['user_id'] = $param['user_id'];
            $d['is_duties'] = $param['is_duties']??0;

            $name = $param['name']??'';
            $name_str = $Translation->translationSelf($name);

            $d['name'] = $name_str['zh'];
            $d['name_ru'] = $name_str['ru'];

            $d['sn'] = $param['sn']??'';
            $d['number'] = $param['number']??0;
            $d['price'] = $param['price']??0;
            $d['create_at'] = date('Y-m-d H:i:s');

            $content = $param['content']??'';

            $str = '';
            $attachment = '';
            $packing = '';
            $invoice = '';
            $cmr = '';

            $insertGetId = self::insertGetId($d);
            if($insertGetId){

                $RemarkModel = new RemarkModel();
                $content_id = 0;
                if(!empty($content)){
                    $content_id = $RemarkModel::remark_id($content, $this->table, $insertGetId);
                }


                if (!empty($param['image'])) {
                    $list_arr = explode(',', $param['image']);
                    foreach ($list_arr as $k => &$v) {
                        $str .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                    }
                    $str = trim($str, ',');
                }

                if (!empty($param['attachment'])) {
                    $attachment_arr = explode(',', $param['attachment']);
                    foreach ($attachment_arr as $k => &$v) {
                        $attachment .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                    }
                    $attachment = trim($attachment, ',');
                }

                if (!empty($param['packing'])) {
                    $packing_arr = explode(',', $param['packing']);
                    foreach ($packing_arr as $k => &$v) {
                        $packing .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                    }
                    $packing = trim($packing, ',');
                }

                if (!empty($param['invoice'])) {
                    $invoice_arr = explode(',', $param['invoice']);
                    foreach ($invoice_arr as $k => &$v) {
                        $invoice .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                    }
                    $invoice = trim($invoice, ',');
                }

                if (!empty($param['cmr'])) {
                    $cmr_arr = explode(',', $param['cmr']);
                    foreach ($cmr_arr as $k => &$v) {
                        $cmr .= $AttachmentModel->insertGetId(['user_id' => $param['user_id'], 'table_name' => $this->table, 'table_id' => $insertGetId, 'path' => $v]) . ',';
                    }
                    $cmr = trim($cmr, ',');
                }


                self::where(["id" => $insertGetId])->update(['image_id' => $str,'attachment_id' => $attachment,
                    'invoice_id' => $invoice,'packing_id' => $packing,'cmr_id' => $cmr, 'content_id' => $content_id]);
            }

            Db::commit();
            return self::find([$insertGetId]);
        }catch (\Exception $e){
            Db::rollback();
            return 0;
        }
    }


    /**
     * @param $param
     * @return ClearanceModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 历史记录
     * @author: dongdong
     * @date: 2025/2/19 11:35
     */
    public function history_list($param){
        $CarModel = new CarModel();
        $page = $param['page'] ?? 1;
        $user_id = $param['user_id'] ?? '';
        $limit = $param['limit'] ?? 10;
        $page = ($page - 1) * $limit;
        $driverModel = new DriverModel();
        $history = [];
        $lists = Db::table("store_history_list")->where(['user_id'=>$user_id])->order("id desc")->limit($page,$limit)->select();
        foreach ($lists as $key =>&$val){
            $list = $CarModel->where(["id"=>$val['car_id']])->select();
            $val['car_list'] = [];
            foreach ($list as $k => &$v) {
                $v['car_category_name'] = $CarModel->car_category_name($v['car_category_id']);
                $v['area'] = Db::connect('fast_mysql')->table('fa_area')->where(["id" => $v['current_city_id']])->find();
                $v['driver'] = $driverModel->where(["id" => $v['driver_id']])->find();

                if (!empty($v['driver']['bind_user_id'])) {
                    $v['user'] = Db::connect("fast_mysql")->table("fa_user")->field("id,username,username_ru,mobile,level,avatar")->where(["id" => $v['driver']['bind_user_id']])->find();
                    $v['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v['driver']['bind_user_id']])->field("identity_id,country,profile,profile_ru")->find();
                } else {
                    $v['user'] = Db::connect("fast_mysql")->table("fa_user")->field("id,username,username_ru,mobile,level,avatar")->where(["id" => $v['user_id']])->find();
                    $v['user_info'] = Db::connect("fast_mysql")->table("fa_user_info")->where(["user_id" => $v['user_id']])->field("identity_id,country,profile,profile_ru")->find();
                }

                array_push($val['car_list'], $v);
            }

            foreach ($val['car_list'] as $k => &$v) {
                $cfd = [];
                $mdd = [];
                $tt = [];
                if ($v['transport_list']) {
                    $transport = explode(';', $v['transport_list']);
                    foreach ($transport as $kk => &$vv) {
                        $str = explode(',', $vv);
                        if (($str) && ($str[0])) {
                            $cfd[] = Db::connect('fast_mysql')->table('fa_area')->field("id,shortname,shortname_ru,name,name_ru,mergename,mergename_ru")->where(["id" => $str[0]])->find();
                        }
                        if (($str) && ($str[1])) {
                            $mdd[] = Db::connect('fast_mysql')->table('fa_area')->field("id,shortname,shortname_ru,name,name_ru,mergename,mergename_ru")->where(["id" => $str[1]])->find();
                        }
                    }
                    $v['cfd'] = $cfd;
                    $v['mdd'] = $mdd;


                    $result = explode(';', $v['transport_list']);
                    foreach ($result as $k6 => &$v6) {
                        $dd = explode(',', $v6);
                        array_push($tt, ['departure_city' => $this->city($dd[0]), 'reach_city' => $this->city($dd[1])]);
                    }
                    $v['transport_arr'] = $tt;
                }
            }
            array_push($history,$val);
        }

        return $history;
    }


    /**
     * @param $id
     * @return array|mixed|\think\db\BaseQuery|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 城市
     * @author: dongdong
     * @date: 2025/2/17 15:32
     */
    public function city($id)
    {
        return Db::connect('fast_mysql')->table("fa_area")->field("id,shortname,shortname_ru,name,name_ru,mergename,mergename_ru")->where("id=$id")->find();
    }

    /**
     * @param $param
     * @notes 插入历史记录
     * @author: dongdong
     * @date: 2025/2/19 16:11
     */
    public function insert_history($param){
        $d['user_id'] = $param['user_id'];
        $d['car_id'] = $param['car_id'];
        $d['type'] = $param['type'];
        $d['create_at'] = date('Y-m-d H:i:s');
        Db::table("store_history_list")->insert($d);
    }


    /**
     * @param $id
     * @return ClearanceModel|array|mixed|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @notes 详情
     * @author: dongdong
     * @date: 2025/2/19 15:55
     */
    public function info($id){
        if($id){
            $find = self::where(['id'=>$id])->find();
            $Remark = new RemarkModel();
            $AttachmentModel = new AttachmentModel();

            $find['content'] = $Remark->info($find['content_id']);
            $find['attachment'] = $AttachmentModel->lists($this->table,$find['attachment_id']);
            $find['packing'] = $AttachmentModel->lists($this->table,$find['packing_id']);
            $find['invoice'] = $AttachmentModel->lists($this->table,$find['invoice_id']);
            $find['cmr'] = $AttachmentModel->lists($this->table,$find['cmr_id']);
            $find['image'] = $AttachmentModel->lists($this->table,$find['image_id']);

            return $find;
        }else{
            return [];
        }
    }

}